﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using System.Web.UI.WebControls;

namespace AutocompleteDemo.Layouts
{
    public partial class ServiceCreate : LayoutsPageBase
    {
        // Fields
        protected IisWebServiceApplicationPoolSection m_applicationPoolSection;
        protected TextBox m_asAppName;
        protected RequiredFieldValidator m_asAppNameValidator;
        protected CheckBox m_default;
        protected CustomValidator m_uniqueNameValidator;

        // Methods
        protected void CancelButtonClick(object sender, EventArgs e)
        {
            this.SendResponseForPopUI();
        }

        private void CreateNewServiceApp()
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.Begin();
                try
                {
                    string name = this.m_asAppName.Text.Trim();
                    if (SPFarm.Local == null)
                        throw new NullReferenceException("SPFarm.Local");

                    // Create the service applicaton
                    AutoCompletionServiceApplication serviceApplication = 
                        AutoCompletionService.Local.CreateApplication(name, false, (this.m_applicationPoolSection == null) ? null : this.m_applicationPoolSection.GetOrCreateApplicationPool());
                    
                    if (serviceApplication == null)
                        throw new NullReferenceException("AutoCompletionServiceApplication");

                    // It seems redundant, but update needs to be called 
                    // before AND after the endpoint gets provisioned.
                    serviceApplication.Update();
                    serviceApplication.AddServiceEndpoint(string.Empty, SPIisWebServiceBindingType.Http);
                    
                    // Could add a secure endpoint like this 
                    //serviceApplication.AddServiceEndpoint("https", SPIisWebServiceBindingType.Https, "https");
                    
                    serviceApplication.Update(true);
                    serviceApplication.Provision();

                    // Create the service application proxy
                    ((AutoCompletionServiceApplicationProxy)AutoCompletionService.Local.CreateProxy(name, false, serviceApplication, null)).Update(true);
                    if (this.m_default.Checked)
                    {
                        serviceApplication.RegisterAsDefaultApplication();
                    }
                }
                catch (Exception ex)
                {
                    throw new SPException("Failed to create service applicaton", ex);
                }
            }
        }


        protected void OkButton_Click(object sender, EventArgs e)
        {
            if (this.Page.IsValid)
            {
                if (this.ApplicationId == Guid.Empty)
                {
                    this.CreateNewServiceApp();
                }
                this.SendResponseForPopUI();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ((DialogMaster)this.Page.Master).OkButton.Click += new EventHandler(this.OkButton_Click);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!this.Page.IsPostBack)
            {
                Guid applicationId = this.ApplicationId;
                if (applicationId != Guid.Empty)
                {
                    if (SPFarm.Local == null)
                    {
                        throw new NullReferenceException("SPFarm.Local");
                    }

                    AutoCompletionServiceApplication application = 
                        SPFarm.Local.GetObject(applicationId) as AutoCompletionServiceApplication;

                    if (application != null)
                    {
                        this.m_asAppName.Text = application.Name;
                    }
                    else
                    {
                        throw new Exception();
                    }
                }
            }
        }

        protected void ValidateUniqueName(object sender, ServerValidateEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }
            if (SPFarm.Local == null)
            {
                throw new NullReferenceException("SPFarm.Local");
            }

            string name = this.m_asAppName.Text.Trim();
            AutoCompletionServiceApplication applicationByName = AutoCompletionServiceApplication.GetLocalApplicationByName(name);
            bool flag = true;
            if (applicationByName != null)
            {
                flag = false;
            }
            e.IsValid = flag;
            this.m_uniqueNameValidator.ErrorMessage = "The specified service application name is already in use.";
        }

        // Properties
        private Guid ApplicationId
        {
            get
            {
                Guid empty = Guid.Empty;
                if (base.Request.QueryString != null)
                {
                    string str = base.Request.QueryString["appid"];
                    if (string.IsNullOrEmpty(str))
                    {
                        return empty;
                    }
                    try
                    {
                        empty = new Guid(str);
                    }
                    catch (FormatException)
                    {
                        throw new Exception();
                    }
                }
                return empty;
            }


        }
    }
}
